import string
import redis
import random
import json
import datetime


from rest_framework.viewsets import ViewSet
from rest_framework.response import Response
from rest_framework import status
from zhdate import ZhDate

from django.contrib.auth.hashers import make_password, check_password

from captcha.image import ImageCaptcha
from django.http import HttpResponse
from user.models import *
from user.serializer import *
from clbum.serializer import *
from study.models import *
from study.serializer import *
from utils.jwt_token import MyJwt

from utils.pay import MyAlipay
from utils.jwt_token import check_login
from django.core.paginator import Paginator
from django.db.models import Q


# 分页函数
def pag(self, userinfo, pag_size, pagination):
    paginator = Paginator(userinfo, pag_size)

    page = paginator.page(pagination)

    return page


# 首页
class HomeView(ViewSet):
    def slidechow(self, request):
        try:
            carousel = CarouselModel.objects.all()
            ser = CarouselSer(carousel, many=True).data
            return Response({"code": status.HTTP_200_OK, "msg": "成功", "data": ser})
        except Exception as e:
            print("失败", e)
            return Response({"code": status.HTTP_500_INTERNAL_SERVER_ERROR, "msg": "失败"})


# 用户
class UserView(ViewSet):

    # 图片验证码
    def img(self, request, uuid):
        number = string.ascii_letters + string.digits
        img_code = "".join(random.sample(number, 4))
        print("img_code", img_code)
        img_ser = ImageCaptcha()
        img_code_num = img_ser.generate(img_code)
        redis_conn = redis.Redis(host='localhost', port=6379, db=0)
        # 根据uuid构造key
        key = "img:%s" % uuid
        # 设置过期时间
        redis_conn.set(key, img_code, ex=300)
        # 关闭
        redis_conn.close()
        return HttpResponse(img_code_num, content_type="image/png")

    # 登录
    def login(self, request, uuid):
        account = request.data.get("account")
        password = request.data.get("password")
        image_code = request.data.get("code")

        user = UserModel.objects.filter(account=account, is_delete=False).first()
        if not user:
            return Response({"code": status.HTTP_400_BAD_REQUEST, "msg": "没有此员工！！"})

        print("user", user)

        if check_password(password, user.password):

            key = "img:%s"%uuid
            print("key", key)
            redis_conn = redis.Redis(host='localhost', port=6379, db=0)
            code = redis_conn.get(key)
            print("code", code)

            if not code:
                return Response({"code": status.HTTP_204_NO_CONTENT, "msg": "图片验证码过期"})
            print("验证码:", code)

            if code.decode().lower() == image_code.lower():

                myjwt = MyJwt()

                ser = UserSer(user).data

                # 添加登录记录
                UserLoginModel.objects.create(user_id=user.id)

                return Response({
                    "code": status.HTTP_200_OK,
                    "msg": "登录成功!",
                    "token": myjwt.encode({'id': user.id, "account": user.account}),
                    "data": ser
                })

            return Response({"code": status.HTTP_204_NO_CONTENT, "msg": "图片验证失败"})

        return Response({"code": status.HTTP_500_INTERNAL_SERVER_ERROR, "msg": "用户名或密码错误！"})

    # 注册
    def register(self, request):
        account = request.data.get("account")
        password = request.data.get("password")
        name = request.data.get("name")
        mobile = request.data.get("mobile")
        classs_id = request.data.get("classs_id")
        user_id = request.data.get("user_id")
        role_id = request.data.get("role_id")

        print(account, name, password, classs_id, user_id, role_id)

        try:

            # 班级
            classs = ClasssModel.objects.filter(name=classs_id, is_delete=False)
            ser = ClasssSer(classs, many=True).data
            for i in ser:
                if i.get("name") == classs_id:
                    classs_id = i.get("id")
                    print("classs_id", classs_id)

            # 角色
            role = RoleModel.objects.filter(name=role_id, is_delete=False)
            role_ser = RoleSer(role, many=True).data
            for i in role_ser:
                if i.get("name") == role_id:
                    role_id = i.get("id")
                    print("role_id", role_id)

            user = UserModel.objects.filter(account=account, password=password, is_delete=False).first()
            if user:
                return Response({"code": status.HTTP_204_NO_CONTENT, "msg": "名称已经存在"})

            pwd = make_password(password)
            user_data = {
                "account": account,
                "password": pwd,
                "classs": classs_id,
                "user": user_id,
                "role": role_id
            }
            user_ser = UserSer(data=user_data)
            if not user_ser.is_valid():
                return Response({'code': status.HTTP_400_BAD_REQUEST, 'msg': user_ser.errors})
            user_ser.save()

            # 查找最新注册的用户
            user = UserModel.objects.filter(account=account, password=pwd,  is_delete=False).first()
            user = UserSer(user).data
            print("user", user)

            info = UserInfoModel.objects.filter(user_id=user["id"], is_delete=False).first()
            if info:
                return Response({"code": status.HTTP_204_NO_CONTENT, "msg": "此人信息已经存在"})

            # 添加个人信息
            user_info = {
                "name": name,
                "birthday": "2022-09-23",
                "mobile": mobile,
                "img": "123",
                "user": user["id"]
            }
            user_info = UserInfoSer(data=user_info)
            print("user_info", user_info)
            if not user_info.is_valid():
                return Response({'code': status.HTTP_400_BAD_REQUEST, 'msg': user_info.errors})
            user_info.save()

            return Response({"code": status.HTTP_200_OK, "msg": "注册成功"})
        except Exception as e:
            print("失败的原因", e)
            return Response({"code": status.HTTP_500_INTERNAL_SERVER_ERROR, "msg": "失败"})

    # 忘记密码
    def upuser(self, request):
        try:
            account = request.data.get("account")
            password = request.data.get("password")

            if not all([account, password]):
                return Response({"code": status.HTTP_204_NO_CONTENT, "msg": "用户名和密码不能为空"})

            try:
                user = UserModel.objects.filter(account=account, is_delete=False)

                if not user:
                    return Response({'code': 400, 'msg': '用户不存在'})

                if account:
                    user.update(account=account)
                if password:
                    hash_pwd = make_password(password, "pbkdf2_sha256")
                    user.update(password=hash_pwd)
                return Response({'code': 200, 'msg': '修改成功'})
            except Exception as e:
                print('失败的原因：', str(e))
                return Response({'code': 400, 'msg': '修改失败'})


        except Exception as e:
            print('修改失败的原因', e)
            return Response({"code": 500, "msg": "服务器错误"})


# 个人信息
class UserInfoView(ViewSet):

    # 查看 老师 学生个人信息
    @check_login
    def user_info(self, request):
        user_id = self._cuser.id
        print("user_id", user_id)

        try:
            user = UserModel.objects.filter(id=user_id, is_delete=False).first()
            user_ser = UserSer(user).data

            print("user", user_ser)

            info = UserInfoModel.objects.filter(user_id=user_ser['id'], is_delete=False).first()
            ser = UserInfoSer(info).data
            data = {
                "account": user_ser['account'],
                "classs": user_ser['classs_name'],
                "role_name": user_ser['role_name'],
                "name": ser['name'],
                "img": ser['img'],
                "gender": ser['gender'],
                "birthday": ser['birthday'],
                "mobile": ser['mobile']
            }

            return Response({"code": status.HTTP_200_OK, "msg": "成功", "data": data})
        except Exception as e:
            print("错误", e)
            return Response({"code": status.HTTP_500_INTERNAL_SERVER_ERROR, "msg": "失败"})

    # 修改 老师 学生 个人信息
    @check_login
    def upuser_info(self, request):
        user_id = self._cuser.id
        print("user_id", user_id)
        account = request.data.get("account")
        password = request.data.get("password")

        name = request.data.get("name")
        gender = request.data.get("gender")
        birthday = request.data.get("birthday")
        mobile = request.data.get("mobile")

        try:
            user = UserModel.objects.filter(id=user_id, is_delete=False)

            if not user:
                return Response({'code': status.HTTP_400_BAD_REQUEST, 'msg': '用户不存在'})

            user = UserModel.objects.filter(account=account, is_delete=False)
            if user:
                return Response({"code": status.HTTP_204_NO_CONTENT, "msg": "名称已经存在"})

            if account:
                user.update(name=account)
            if password:
                hash_pwd = make_password(password, "pbkdf2_sha256")
                user.update(password=hash_pwd)

            ser = UserSer(user, many=True).data
            user_ser = json.loads(json.dumps(ser))
            for i in user_ser:
                info = UserInfoModel.objects.filter(user_id=i['id'], is_delete=False)

            if not info:
                return Response({'code': status.HTTP_400_BAD_REQUEST, 'msg': '没有此人'})

            info = UserInfoModel.objects.filter(name=name, is_delete=False)

            if info:
                return Response({"code": status.HTTP_204_NO_CONTENT, "msg": "名称已经存在"})

            if name:
                info.update(name=name)

            if gender:
                info.update(gender=gender)
            if birthday:
                info.update(birthday=birthday)
            if mobile:
                info.update(mobile=mobile)

            return Response({"code": status.HTTP_200_OK, "msg": "ok"})
        except Exception as e:
            print("失败", e)
            return Response({"code": status.HTTP_500_INTERNAL_SERVER_ERROR, "msg": "失败"})

    # 删除老师 学生
    @check_login
    def del_info(self, request, pk):
        try:
            user_info = UserModel.objects.filter(id=pk,  is_delete=False)
            if not user_info:
                return Response({"code": status.HTTP_400_BAD_REQUEST, "msg": "没有用户"})

            ser = UserSer(user_info, many=True).data
            user_ser = json.loads(json.dumps(ser))
            for i in user_ser:
                info = UserInfoModel.objects.filter(user_id=i['id'], is_delete=False)
                user_info.update(is_delete=True)
                info.update(is_delete=True)

            return Response({"code": status.HTTP_200_OK, "msg": "成功"})
        except Exception as e:
            print("失败", e)
            return Response({"code": status.HTTP_500_INTERNAL_SERVER_ERROR, "msg": "失败"})


# 登录记录
class UserLoginView(ViewSet):

    # 获取登录记录
    def list_login(self, request):
        try:
            login = UserLoginModel.objects.all().order_by('-create_time')
            ser = UserLoginSer(login, many=True).data
            return Response({"code": status.HTTP_200_OK, "msg": "成功", "data": ser})
        except Exception as e:
            print("失败", e)
            return Response({"code": status.HTTP_500_INTERNAL_SERVER_ERROR, "msg": "失败"})


# 问候语
# __gt 大于
# __lt 小于
# __gte 大于等于
# __lte 小于等于
class GreetingsView(ViewSet):

    # 获取问候语
    @check_login
    def list_greetings(self, request):
        try:
            # 获取当前时间
            times = datetime.datetime.now().hour
            # 查询
            list = GreetingsModel.objects.filter(Q(start_time__lte=times) & Q(end_time__gte=times)).all()
            ser = GreetingsSer(list, many=True).data
            greetings = json.loads(json.dumps(ser))
            # 随机取出一条数据
            rdm = random.choice(greetings)
            return Response({"code": status.HTTP_200_OK, "msg": "成功", "data": rdm})
        except Exception as e:
            print("失败", e)
            return Response({"code": status.HTTP_500_INTERNAL_SERVER_ERROR, "msg": "失败"})

    # 获取节日问候语
    @check_login
    def list_fesgreetings(self, request):
        try:
            now_date = datetime.datetime.now().strftime('%Y-%m-%d')
            now_date1 = now_date.split('-')
            now_date2 = datetime.datetime(int(now_date1[0]), int(now_date1[1]), int(now_date1[2]))
            date = ZhDate.from_datetime(now_date2)

            # 找出date_type =1 的问候语
            fes = FesGreetingsModel.objects.filter(date_type=1, is_delete=False).all()
            fes = FesGreetingsSer(fes, many=True).data
            fes = json.loads(json.dumps(fes))

            # 找出date_type =2 的问候语
            fes_greetings = FesGreetingsModel.objects.filter(date_type=2, is_delete=False).all()
            fes_greetings = FesGreetingsSer(fes_greetings, many=True).data
            fes_greetings = json.loads(json.dumps(fes_greetings))

            date = str(date)

            for i in fes:
                if now_date[5:] == i['holiday_date']:
                    return Response({'code': status.HTTP_200_OK, 'msg': '获取成功', 'data': i})

            for j in fes_greetings:
                if date[7:] == j['holiday_date']:
                    return Response({'code': status.HTTP_200_OK, 'msg': '获取成功', 'data': j})

            return Response({'code': status.HTTP_200_OK, 'msg': '当前不是任何节日'})
        except Exception as e:
            print("失败", e)
            return Response({"code": status.HTTP_500_INTERNAL_SERVER_ERROR, "msg": "失败"})


# 消息
class MessageView(ViewSet):

    # 发送消息
    @check_login
    def add_msg(self, request):
        user = self._cuser.id
        name = request.data.get("name")
        users = request.data.get("users")

        print(user, name, users)

        try:
            list = UserModel.objects.filter(account=users, is_delete=False)
            if not list:
                return Response({"code": status.HTTP_204_NO_CONTENT, "msg": "没有此用户"})
            user_ser = UserSer(list, many=True).data
            user_ser = json.loads(json.dumps(user_ser))
            for i in user_ser:
                print("i", i)
                if i["account"] == users:
                    users = i.get("id")
                    print("users", users)
            data = {
                "name": name,
                "user": user,
                "users": users
            }
            ser = MsgSer(data=data)
            if not ser.is_valid():
                return Response({"code": status.HTTP_400_BAD_REQUEST, "msg": ser.errors})
            ser.save()
            return Response({"code": status.HTTP_200_OK, "msg": "成功"})
        except Exception as e:
            print("失败", e)
            return Response({"code": status.HTTP_500_INTERNAL_SERVER_ERROR, "msg": "失败"})

    # 接收消息
    @check_login
    def list_msg(self, request):
        user_id = self._cuser.id
        try:
            msg = MessageModel.objects.filter(users_id=user_id, is_delete=False).all()
            ser = MsgSer(msg, many=True).data
            return Response({"code": status.HTTP_200_OK, "msg": "成功", "data": ser})
        except Exception as e:
            print("失败", e)
            return Response({"code": status.HTTP_500_INTERNAL_SERVER_ERROR, "msg": "失败"})


# 菜单
class MenuView(ViewSet):

    # 获取菜单
    @check_login
    def list_menu(self, request):

        user_id = self._cuser.id

        try:

            user = UserModel.objects.filter(id=user_id, is_delete=False).first()

            if not user:
                return Response({"code": status.HTTP_204_NO_CONTENT, "msg": "没有此用户"})

            role_menu = RoleMenuModel.objects.filter(role_id=user.role_id, is_delete=False).all()
            role_menu = RoleMenuSer(role_menu, many=True).data
            role_menu = json.loads(json.dumps(role_menu))
            list = []
            for i in role_menu:
                menu = MenuModel.objects.filter(id=i["menu"], menu=None, is_delete=False).first()
                menu = MenuSer(menu).data
                menu = json.loads(json.dumps(menu))
                list.append(menu)
            for i in list:
                menu = MenuModel.objects.filter(menu=i["id"], is_delete=False).all()
                menu = MenuSer(menu, many=True).data
                menu = json.loads(json.dumps(menu))
                i["menu_list"] = menu
            return Response({"code": status.HTTP_200_OK, "msg": "获取成功", "data": list})
        except Exception as e:
            print("获取菜单失败", e)
            return Response({"code": status.HTTP_500_INTERNAL_SERVER_ERROR, "msg": "获取失败"})

    # 添加菜单
    @check_login
    def add_menu(self, request):
        user_id = self._cuser.id
        name = request.data.get("name")
        path = request.data.get("path")
        menu_id = request.data.get("menu_id")
        role_id = request.data.get("role_id")

        try:

            user = UserModel.objects.filter(id=user_id, is_delete=False).first()

            if not user:
                return Response({"code": status.HTTP_204_NO_CONTENT, "msg": "没有此用户"})

            menu = MenuModel.objects.filter(name=name, is_delete=False).first()
            if menu:
                return Response({"code": status.HTTP_400_BAD_REQUEST, "msg": "此菜单已经存在!!!"})
            print("menu", menu)
            if menu_id:
                menu = MenuModel.objects.filter(id=menu_id,menu=None, is_delete=False).first()
                if not menu:
                    return Response({"code": status.HTTP_400_BAD_REQUEST, "msg": "没有此主菜单"})
            MenuModel.objects.create(name=name, path=path, menu=menu_id)

            menu = MenuModel.objects.filter(name=name, path=path, menu=menu_id, is_delete=False).first()
            print("menu", menu)

            role = RoleModel.objects.filter(id=role_id, is_delete=False).first()
            if not role:
                return Response({"code": status.HTTP_400_BAD_REQUEST, "msg": "没有此角色"})

            RoleMenuModel.objects.create(role_id=role_id, menu_id=menu.id)
            return Response({"code": status.HTTP_200_OK, "msg": "添加菜单成功"})
        except Exception as e:
            print("失败", e)
            return Response({"code": status.HTTP_500_INTERNAL_SERVER_ERROR, "msg": "添加菜单失败"})

    # 修改菜单
    @check_login
    def up_menu(self, request, pk):
        user_id = self._cuser.id

        name = request.data.get("name")
        path = request.data.get("path")
        try:
            user = UserModel.objects.filter(id=user_id, is_delete=False).first()
            if not user:
                return Response({"code": status.HTTP_204_NO_CONTENT, "msg": "没有此用户"})

            menu = MenuModel.objects.filter(id=pk, is_delete=False)
            if not menu:
                return Response({"code": status.HTTP_400_BAD_REQUEST, "msg": "没有此菜单"})

            menu_lst = MenuModel.objects.filter(name=name, path=path, is_delete=False).first()
            if menu_lst:
                return Response({"code": status.HTTP_400_BAD_REQUEST, "msg": "此菜单已经存在!!!"})

            if name:
                menu.update(name=name)
            if path:
                menu.update(path=path)
            return Response({"code": status.HTTP_200_OK, "msg": "修改菜单成功"})
        except Exception as e:
            print("失败", e)
            return Response({"code": status.HTTP_500_INTERNAL_SERVER_ERROR, "msg": "修改菜单失败"})

    # 删除菜单
    @check_login
    def del_menu(self, request, pk):

        user_id = self._cuser.id

        try:
            user = UserModel.objects.filter(id=user_id, is_delete=False).first()
            if not user:
                return Response({"code": status.HTTP_204_NO_CONTENT, "msg": "没有此用户"})

            menu = MenuModel.objects.filter(id=pk, is_delete=False)
            if not menu:
                return Response({"code": status.HTTP_400_BAD_REQUEST, "msg": "没有此菜单"})

            menu.update(is_delete=True)

            return Response({"code": status.HTTP_200_OK, "msg": "删除菜单成功"})
        except Exception as e:
            print("失败", e)
            return Response({"code": status.HTTP_500_INTERNAL_SERVER_ERROR, "msg": "删除菜单失败"})


# 搜索记录
class SearchView(ViewSet):

    # 添加搜索记录
    @check_login
    def add_search(self, request):
        user_id = self._cuser.id
        name = request.data.get("name")

        try:

            user = UserModel.objects.filter(id=user_id, is_delete=False).first()
            if not user:
                return Response({"code": status.HTTP_204_NO_CONTENT, "msg": "没有此用户"})

            contents = ContentsModel.objects.filter(title=name, is_delete=False).all()
            print("contents", contents)

            return Response({"code": status.HTTP_200_OK, "msg": "搜索成功"})
        except Exception as e:
            print("失败", e)
            return Response({"code": status.HTTP_500_INTERNAL_SERVER_ERROR, "msg": "搜索失败"})

    # 获取我的搜索记录
    @check_login
    def list_search(self, request):
        user_id = self._cuser.id
        try:

            user = UserModel.objects.filter(id=user_id, is_delete=False).first()
            print("user", user)
            if not user:
                return Response({"code": status.HTTP_204_NO_CONTENT, "msg": "没有此用户"})

            search = SearchModel.objects.filter(user_id=user_id, is_delete=False).all()
            search = SearchSer(search, many=True).data
            print("search", search)
            return Response({"code": status.HTTP_200_OK, "msg": "搜索成功", "data": search})
        except Exception as e:
            print("失败", e)
            return Response({"code": status.HTTP_500_INTERNAL_SERVER_ERROR, "msg": "搜索失败"})


# 弹幕
class BarrageView(ViewSet):

    # 发送弹幕
    @check_login
    def add_barrage(self, request):
        user_id = self._cuser.id
        contents_id = request.data.get("contents_id")
        name = request.data.get("name")
        like = request.data.get("like")

        try:
            user = UserModel.objects.filter(id=user_id, is_delete=False).first()
            if not user:
                return Response({"code": status.HTTP_204_NO_CONTENT, "msg": "没有此用户"})

            contents = ContentsModel.objects.filter(id=contents_id, is_delete=False).first()
            if not contents:
                return Response({"code": status.HTTP_204_NO_CONTENT, "msg": "没有此内容"})
            BarrageModel.objects.create(name=name, user_id=user_id, contents_id=contents_id, like=like)

            return Response({"code": status.HTTP_200_OK, "msg": "发送成功"})
        except Exception as e:
            print("失败", e)
            return Response({"code": status.HTTP_500_INTERNAL_SERVER_ERROR, "msg": "发送失败"})


# 订单
class OrderView(ViewSet):

    myalipay = MyAlipay()

    # 提交订单
    @check_login
    def add_order(self, request):
        user_id = self._cuser.id
        pay_method = request.data.get("pay_method")
        total_count = request.data.get("total_count")
        total_amount = request.data.get("total_amount")
        print(user_id, pay_method, total_count, total_amount)
        try:
            user = UserModel.objects.filter(id=user_id, is_delete=False).first()
            print("user", user)
            if not user:
                return Response({"code": status.HTTP_400_BAD_REQUEST, "msg": "没有此用户"})

            order_id = datetime.datetime.now().timestamp()
            # 订单编号
            order = OrderModel.objects.filter(user_id=user_id, pay_method=pay_method, total_count=total_count, total_amount=total_amount, order_id=order_id).first()
            if not order:
                return Response({"code": status.HTTP_400_BAD_REQUEST, "msg": "此订单已经存在"})
            order = OrderModel.objects.create(user_id=user_id, pay_method=pay_method, total_count=total_count, total_amount=total_amount, order_id=order_id)

            return_url = "http://127.0.0.1:8000/index/order"
            url = self.myalipay.get_pay_url(order_id, total_amount, return_url)
            return Response({"code": status.HTTP_200_OK, "msg": "创建成功", "url": url})
        except Exception as e:
            print("失败", e)
            return Response({"code": status.HTTP_500_INTERNAL_SERVER_ERROR, "msg": "提交失败"})

    # 判断订单是否支付成功
    @check_login
    def check_order(self, request):
        try:
            order_id = request.data.get("order_id")
            order = OrderModel.objects.filter(order_id=order_id, is_delete=False)

            if not order:
                return Response({"code": status.HTTP_400_BAD_REQUEST, "msg": "没有此订单"})

            if not self.myalipay.check(order_id):
                return Response({"code": status.HTTP_400_BAD_REQUEST, "msg": "没有支付"})

            order.update(pay_state=1)
            return Response({"code": status.HTTP_200_OK, "msg": "支付成功"})

        except Exception as e:
            print("判断支付的结果为", e)
            return Response({"code": status.HTTP_500_INTERNAL_SERVER_ERROR, "msg": "支付失败"})

    # 获取用户的所有订单
    @check_login
    def list_order(self, request):
        try:
            user_id = self._cuser.id

            user = UserModel.objects.filter(id=user_id, is_delete=False).first()
            print("user", user)
            if not user:
                return Response({"code": status.HTTP_400_BAD_REQUEST, "msg": "没有此用户"})

            order = OrderModel.objects.filter(user_id=user_id, is_delete=False).all().order_by('-create_time')
            order_ser = OrderSer(order, many=True).data

            return Response({"code": status.HTTP_200_OK, "msg": "获取成功", "data": order_ser})
        except Exception as e:
            print("获取失败的原因", e)
            return Response({"code": status.HTTP_500_INTERNAL_SERVER_ERROR, "msg": "获取失败"})

    # 获取没有支付的订单
    @check_login
    def not_order(self, request):
        try:
            user_id = self._cuser.id
            user = UserModel.objects.filter(id=user_id, is_delete=False).first()
            print("user", user)
            if not user:
                return Response({"code": status.HTTP_400_BAD_REQUEST, "msg": "没有此用户"})
            order = OrderModel.objects.filter(user_id=user_id, pay_state=0, is_delete=False).all().order_by('-create_time')
            order_ser = OrderSer(order, many=True)

            return Response({"code": status.HTTP_200_OK, "msg": "获取成功", "data": order_ser.data})
        except Exception as e:
            print("获取失败的原因", e)
            return Response({"code": status.HTTP_500_INTERNAL_SERVER_ERROR, "msg": "获取失败"})

    # 获取用户支付的订单
    @check_login
    def order_pay(self, request):
        try:
            user_id = self._cuser.id
            user = UserModel.objects.filter(id=user_id, is_delete=False).first()
            print("user", user)
            if not user:
                return Response({"code": status.HTTP_400_BAD_REQUEST, "msg": "没有此用户"})

            order = OrderModel.objects.filter(user_id=user_id, pay_state=1, is_delete=False).all().order_by('-create_time')
            order_ser = OrderSer(order, many=True)

            return Response({"code": status.HTTP_200_OK, "msg": "获取成功", "data": order_ser.data})
        except Exception as e:
            print("获取失败的原因", e)
            return Response({"code": status.HTTP_500_INTERNAL_SERVER_ERROR, "msg": "获取失败"})

    # 获取没有支付的订单的地址
    @check_login
    def not_order_get(self, request, pk):
        try:
            order = OrderModel.objects.filter(id=pk, pay_method=1, pay_state=0, is_delete=False).first()
            print('--------', order)
            return_url = "http://127.0.0.1:8080/index/order/"
            pay_url = self.myalipay.get_pay_url(order.order_id, str(order.total_amount), return_url)
            print('-======', pay_url)
            order.pay_state = 1
            order.save()
            return Response({"code": status.HTTP_200_OK, 'msg': '正在跳转支付地址', 'pay_url': pay_url})

        except Exception as e:
            print("获取没有支付的订单失败", e)
            return Response({"code": status.HTTP_500_INTERNAL_SERVER_ERROR, 'msg': "跳转失败"})

    # 删除订单
    @check_login
    def order_del(self, request, pk):
        try:
            user_id = self._cuser.id
            user = UserModel.objects.filter(id=user_id, is_delete=False).first()
            if not user:
                return Response({"code": status.HTTP_204_NO_CONTENT, "msg": "没有此用户"})

            order = OrderModel.objects.filter(id=pk, user_id=user_id, is_delete=False)
            if not order:
                return Response({"code": status.HTTP_400_BAD_REQUEST, "msg": "没有此订单"})

            order.update(is_delete=True)

            return Response({"code": status.HTTP_200_OK, "msg": "删除订单成功"})
        except Exception as e:
            print("删除订单失败", e)
            return Response({"code": status.HTTP_500_INTERNAL_SERVER_ERROR, "msg": "删除订单失败"})

    # 获取订单的详情
    @check_login
    def order_get_details(self, request, pk):
        try:
            user_id = self._cuser.id
            user = UserModel.objects.filter(id=user_id, is_delete=False).first()
            print("user", user)
            if not user:
                return Response({"code": status.HTTP_400_BAD_REQUEST, "msg": "没有此用户"})

            order = OrderModel.objects.filter(id=pk, user_id=user_id, is_delete=False).first()

            order_ser = OrderSer(order)
            return Response({"code": status.HTTP_200_OK, "msg": "获取订单详情成功", "data": order_ser.data})

        except Exception as e:
            print("获取详情失败的原因:", e)
            return Response({"code": status.HTTP_500_INTERNAL_SERVER_ERROR, "msg": "获取详情失败"})

    # 取消支付订单
    @check_login
    def not_order_del(self, request, pk):
        try:
            user_id = self._cuser.id

            user = UserModel.objects.filter(id=user_id, is_delete=False).first()
            if not user:
                return Response({"code": status.HTTP_204_NO_CONTENT, "msg": "没有此用户"})

            order = OrderModel.objects.filter(id=pk, user_id=user_id, pay_method=1, pay_state=0, is_delete=False)
            if not order:
                return Response({"code": status.HTTP_400_BAD_REQUEST, "msg": "没有此订单"})

            order.update(is_delete=True)

            return Response({"code": status.HTTP_200_OK, "msg": "取消支付成功"})
        except Exception as e:
            print("取消失败", e)
            return Response({"code": status.HTTP_500_INTERNAL_SERVER_ERROR, "msg": "取消支付失败"})

